/*
 * usart.c
 *
 * Created: 05.09.2012 16:06:06
 *  Author: bardbakk
 */
#define F_CPU 4915200

#include <avr/io.h> 
#include <avr/interrupt.h>
#include <stdio.h>

#include "USART.h"


void USART_transmit(unsigned char data)
{
	while(!(UCSR0A & (1<<UDRE0)))
	{
	}
	UDR0=data;
}

unsigned char USART_receive()
{
	unsigned char receivedByte = UDR0;
	USART_msg_rcvd = 0;		
	return receivedByte;
}

void USART_init(unsigned int baudrate)
{
	USART_msg_rcvd = 0;
	unsigned int baud;
	
	baud = ((F_CPU)/(16UL*baudrate)) - 1;
	
	cli();
	UBRR0H = (unsigned char)(baud>>8);
	UBRR0L = (unsigned char)baud;
	
	//Enables receive, transmit and receive interrupt
	UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0);
	
	//Enables use of UCSRC and sets frame format: 2 stop bits, 8 bits. 
	UCSR0C = (1<<URSEL0)|(1<<USBS0)|(3<<UCSZ00);

	
	//TESTING END
		
	sei();
	
	//Link printf to USART_transmit
	fdevopen(USART_transmit, USART_receive);
}

ISR(USART0_RXC_vect)
{
 	USART_msg_rcvd = 1;
}